package nancal.mp.mvc.dev

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import nancal.mp.db.mongo.entity.dev.*
import nancal.mp.db.mongo.entity.yapi.user
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.*
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.CipherUtil
import nbcp.base.utils.MyUtil
import nbcp.mvc.sys.*
import nbcp.myoql.db.mongo.*

import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * Created by CodeGenerator at 2022-06-09 16:13:56
 */
@Api(description = "YApiUser", tags = arrayOf("YApiUser"))
@RestController
@RequestMapping("/dev/yapi-user")
class YapiUserController {

    @ApiOperation("列表")
    @PostMapping("/list")
    fun list(
        id: Int, //当列表列新一条后，刷新时使用
        username: String,
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>,
        request: HttpServletRequest
    ): ListResult<user> {

        mor.yapi.user.query()
                .apply {
                    if (id.HasValue) {
                        this.where { it.id mongoEquals id }
                    }
                    if (username.HasValue) {
                        this.where { it.username mongoLike username }
                    }
                }
                .orderByAsc { it.id }
                .withPager(query)
                .toListResult()
                .apply {
                    return this;
                }
    }

    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
            @Require id: Int,
            request: HttpServletRequest
    ): ApiResult<user> {
        mor.yapi.user.query()
                .where { it.id mongoEquals id }
                .toEntity()
                .apply {
                    if (this == null) {
                        return ApiResult.error("找不到数据")
                    }

                    return ApiResult.of(this)
                }
    }

    @ApiOperation("更新")
    @PostMapping("/save")
    fun save(
            @org.springframework.web.bind.annotation.RequestBody entity: user,
            request: HttpServletRequest
    ): ApiResult<String> {
        //鉴权
        var userId = request.UserId;

        mor.yapi.user.updateWithEntity(entity)
                .withColumns(request.requestParameterKeys)
                .run {
                    if (entity.id.HasValue) {
                        this.withoutColumn { it.passsalt }
                        this.withoutColumn { it.password }
                        return@run this.execUpdate()
                    } else {
                        //获取最大id { $group: { _id: null, max: { $max: "$_id" } } }
                        var maxId = mor.yapi.user.aggregate()
                                .groupWithId("", JsonMap("max" to JsonMap("\$max" to "\$_id")))
                                .toMap()
                                .get("max")
                                .AsInt();

                        entity.id = maxId + 1;

                        entity.passsalt = MyUtil.getRandomWithLength(10);
                        entity.password = CipherUtil.sha1("123.456" + CipherUtil.sha1(entity.passsalt))
                        return@run this.execInsert();
                    }
                }
                .apply {
                    if (this == 0) {
                        return ApiResult.error("更新失败")
                    }

                    return ApiResult.of(entity.id.toString())
                }
    }


    @ApiOperation("更新密码")
    @PostMapping("/set-pwd/{id}")
    fun set_Pwd(
            @Require id: Int,
            @Require password: String,
            request: HttpServletRequest
    ): JsonResult {
        //鉴权
        var userId = request.UserId;
        var passsalt = MyUtil.getRandomWithLength(10);
        var dbPwd = CipherUtil.sha1(password + CipherUtil.sha1(passsalt))

        mor.yapi.user.update()
                .set { it.passsalt to passsalt }
                .set { it.password to dbPwd }
                .where { it.id mongoEquals id }
                .exec()
                .apply {
                    if (this == 0) {
                        return JsonResult.error("更新失败")
                    }

                    return JsonResult()
                }
    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    fun delete(
            @Require id: Int,
            request: HttpServletRequest
    ): JsonResult {
        //鉴权
        var userId = request.UserId

        mor.yapi.user.delete()
                .where { it.id mongoEquals id }
                .exec()
                .apply {
                    if (this == 0) {
                        return JsonResult.error("删除失败")
                    }
                    //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                    return JsonResult()
                }
    }
}